<?php
namespace Common\TagLib;

use Think\Template\TagLib;

class TagLibCommon extends TagLib {

    /**
     * @var type 
     * 标签定义： 
     *    attr        属性列表
     *    close       标签是否为闭合方式 （0闭合 1不闭合），默认为不闭合
     *    alias       标签别名
     *    level       标签的嵌套层次（只有不闭合的标签才有嵌套层次）
     * 定义了标签属性后，就需要定义每个标签的解析方法了，
     * 每个标签的解析方法在定义的时候需要添加“_”前缀，
     * 可以传入两个参数，属性字符串和内容字符串（针对非闭合标签）。
     * 必须通过return 返回标签的字符串解析输出，在标签解析类中可以调用模板类的实例。
     */
    protected $tags = array(
    	'content'	=> array('attr' => 'key, id, table-name, field, where, order, limit, with-page, page-size, page-tpl, page-setting-mode', 'level'=>3),
    );

    /**
     * content标签解析 循环输出数据集
     * @access public
     * @param array $tag 标签属性
     * @param string $content  标签内容
     * @return string|void
     */
    public function _content($tag, $content) {
		$key = $tag['key'];
		$id = $tag['id'];
		$tableName = $tag['table-name'];		// 要查询的数据表
		$field = $tag['field'];
		$where = $tag['where'];
		$order = $tag['order'];
		
		$withPage = $tag['with-page'];
		
		$pageSettingArray = array(
		    "1"=>'array("listlong"=>"6","first"=>"首页","last"=>"尾页","prev"=>"上一页","next"=>"下一页","list"=>"第*页","jump"=>"select")',
		    "2"=>'array("listlong"=>"6","first"=>"首页","last"=>"尾页","prev"=>"上一页","next"=>"下一页","list"=>"第*页","jump"=>"input")'
		);
    	
		$str .= '';
		$str .= '<?php ';
		$str .= '$model = M("' . $tableName . '");';
		
		if ($withPage == "true") {
			$pageSize = $tag['page-size'];
			$pageTpl = '\'' . $tag['page-tpl'] . '\'';
			$pageSettingMode = $tag['page-setting-mode'] ? $tag['page-setting-mode'] : '1';
		      
			$str .= '$totalSize = $model->where("' . $where . '")->count();';
			$str .= '$page = new \Page($totalSize, ' . $pageSize . ');';
			$str .= '$page->setLinkWraper("li");';
			$str .= '$page->SetPager(\'default\', ' . $pageTpl . ', ' . $pageSettingArray[$pageSettingMode] . ');';
			$str .= '$pagination = $page->show();';
			$str .= '$result = $model->field("' . $field . '")->where("' . $where . '")->order("' . $order . '")->limit($page->firstRow, $page->listRows)->select();';
		} else {
			$limit = $tag['limit'];
			
			$str .= '$result = $model->field("' . $field . '")->where("' . $where . '")->order("' . $order . '")->limit(' . $limit . ')->select();';
		}
		
		if ($key) {
            $str .= 'foreach ($result as $' . $key . ' => $' . $id . '):';
		} else {
		    $str .= 'foreach ($result as $' . $id . '):';
		}
		$str .= '?>';
		$str .= $content;
		$str .= '<?php endforeach ?>';
    	
    	return $str;
    }

}
